/**
 *
 */
package com.sunyard.manage.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xeustechnologies.jtar.TarEntry;
import org.xeustechnologies.jtar.TarOutputStream;

import java.io.*;

/**
 * @author huam.zhou
 * @Description 文件压缩成tar包
 * @date 2018年4月1日 下午3:17:22 
 */
public class JtarUtil {
    /**
     * Description
     */
    private static Log log = LogFactory.getLog(JtarUtil.class);

    /**
     * @param path       文件目录
     * @param merchantCd 商户编号
     * @throws IOException
     * @Description 压缩成tar
     */
    public static void toCompress(File path, String merchantCd) throws IOException {
        FileOutputStream dest;
        TarOutputStream out = null;
        File[] filesToTar;
        BufferedInputStream origin = null;
        try {
            if (!path.exists()) {
                path.mkdir();
            }
            //以商户编号为名字的tar包
            String tarName = path.getAbsolutePath() + "//" + merchantCd + ".tar";
            String endTarName = path.getAbsolutePath() + "//" + merchantCd + ".tar" + "%ok%";
            String[] tempList = path.list();
            dest = new FileOutputStream(tarName);
            out = new TarOutputStream(new BufferedOutputStream(dest));
            if (tempList != null && tempList.length > 0) {
                filesToTar = new File[9];
                for (int i = 0; i < tempList.length; i++) {
                    if (tempList[i].startsWith(merchantCd)) {//取以商户编号为开头的所有档案图片
                        String fileName = path.getAbsolutePath() + "//" + tempList[i];
                        filesToTar[i] = new File(fileName);
                    }
                }
                for (File f : filesToTar) {
                    if (f == null) {
                        continue;
                    }
                    out.putNextEntry(new TarEntry(f, f.getName()));
                    origin = new BufferedInputStream(new FileInputStream(f));
                    int count;
                    byte[] data = new byte[2048];
                    while ((count = origin.read(data)) != -1) {
                        out.write(data, 0, count);
                    }
                    out.flush();
                }
                //ok文件
                File endfile = new File(endTarName);
                if (!endfile.exists() || !endfile.exists()) {
                    endfile.createNewFile();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
            if (origin != null) {
                origin.close();
            }
        }
    }

}
